package neusoft.yuejian_11.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import neusoft.yuejian_11.base.BaseActivity;
import neusoft.yuejian_11.bean.AddpostBean;
import neusoft.yuejian_11.bean.GetInfo;
import neusoft.yuejian_11.bean.SampleInfo;
import neusoft.yuejian_11.listener.RetrofitListener;
import neusoft.yuejian_11.model.UserModel;
import neusoft.yuejian_11.R;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static neusoft.yuejian_11.interF.Const.BASE_URI;

//修改个人信息
public class UpdateInfoActivity extends BaseActivity  implements RetrofitListener {
    private EditText UserName;
    private EditText PassWord;
    private EditText UserPhone;
    private EditText UserEmail;
    private  EditText UserAddress;
    private Button Changebutton;
    private Context context;
    private ImageButton imageButtonBack;
    private RoundImageView touxiang;
    private TextView changtou;
    public String filePath = null;
    private Bitmap mBitmap;
    protected static final int CHOOSE_PICTURE = 0;
    protected static final int TAKE_PICTURE = 1;
    protected static Uri tempUri;
    private static final int CROP_SMALL_PICTURE = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_info);
        initData();
        initView();
        setListener();
        //返回前一页
        changtou.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                upLoadPpicFile(filePath);
            }
        });
        imageButtonBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        touxiang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showChoosePicDialog();
            }
        });
    }

    private void initData() {
        UserModel userModel = new UserModel();
        userModel.getUserInfo(getU_id(), this);
    }

    /**
     * 显示修改图片的对话框
     */
    protected void showChoosePicDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(UpdateInfoActivity.this);
        builder.setTitle("添加图片");
        String[] items = {"选择本地照片", "拍照"};
        builder.setNegativeButton("取消", null);
        builder.setItems(items, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case CHOOSE_PICTURE: // 选择本地照片
                        Intent openAlbumIntent = new Intent(
                                Intent.ACTION_GET_CONTENT);
                        openAlbumIntent.setType("image/*");
                        //用startActivityForResult方法，待会儿重写onActivityResult()方法，拿到图片做裁剪操作
                        startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
                        break;
                    case TAKE_PICTURE: // 拍照
                        Intent openCameraIntent = new Intent(
                                MediaStore.ACTION_IMAGE_CAPTURE);
                        tempUri = Uri.fromFile(new File(Environment
                                .getExternalStorageDirectory(), "temp_image.jpg"));
                        // 将拍照所得的相片保存到SD卡根目录
                        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
                        startActivityForResult(openCameraIntent, TAKE_PICTURE);
                        break;
                }
            }
        });
        builder.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == AddPostActivity.RESULT_OK) {
            switch (requestCode) {
                case TAKE_PICTURE:
                    cutImage(tempUri); // 对图片进行裁剪处理
                    break;
                case CHOOSE_PICTURE:
                    cutImage(data.getData()); // 对图片进行裁剪处理
                    break;
                case CROP_SMALL_PICTURE:
                    if (data != null) {
                        setImageToView(data); // 让刚才选择裁剪得到的图片显示在界面上
                    }
                    break;
            }
        }
    }

    /**
     * 裁剪图片方法实现
     */
    protected void cutImage(Uri uri) {
        if (uri == null) {
            Log.i("alanjet", "The uri is not exist.");
        }
        tempUri = uri;
        Intent intent = new Intent("com.android.camera.action.CROP");
        //com.android.camera.action.CROP这个action是用来裁剪图片用的
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CROP_SMALL_PICTURE);
    }

    /**
     * 保存裁剪之后的图片数据
     */
    protected void setImageToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            mBitmap = extras.getParcelable("data");
            //这里图片是方形的，可以用一个工具类处理成圆形（很多头像都是圆形，这种工具类网上很多不再详述）
            touxiang.setImageBitmap(mBitmap);//显示图片
            //在这个地方可以写上上传该图片到服务器的代码，后期将单独写一篇这方面的博客，敬请期待...
            filePath = saveMyBitmap("1", mBitmap);
        }
    }

    private void upLoadPpicFile(String filePath) {
        Log.e("xxxxxxxxx", filePath + "_-----");
        File file = new File(filePath);
        RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body =
                MultipartBody.Part.createFormData("file", file.getName(), requestFile);
        Call<AddpostBean> call = new UserModel().updatetouxiang(getU_id(), body);
        call.enqueue(new Callback<AddpostBean>() {
            @Override
            public void onResponse(Call<AddpostBean> call,
                                   Response<AddpostBean> response) {
//                Log.d("uploadfile",response.body()+"----");
                try {
                   /* Log.e("Upload", "success:"+response.body());*/
                    Toast.makeText(UpdateInfoActivity.this, "头像修改成功", Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<AddpostBean> call, Throwable t) {
                Log.e("Upload error:", t.getMessage());
            }
        });
    }

    public String saveMyBitmap(String bitName, Bitmap mBitmap) {
        File f = new File("/sdcard/" + bitName + ".jpg");
        String picPath = "/sdcard/" + bitName + ".jpg";

        try {
            f.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            //  DebugMessage.put("在保存图片时出错："+e.toString());
        }
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
        try {
            fOut.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return picPath;
    }
    private  void setListener() {
        Changebutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UserModel userModel = new UserModel();
                String username = UserName.getText().toString();
                String userpass = PassWord.getText().toString();
                String mobilenum = UserPhone.getText().toString();
                String address = UserAddress.getText().toString();
                String emaila = UserEmail.getText().toString();
                userModel.updateUserById(getU_id(),username,userpass,mobilenum,address,emaila,UpdateInfoActivity.this);

            }
        });


    }
    private  void initView() {
        UserName = (EditText) findViewById(R.id.change_name);
        PassWord= (EditText) findViewById(R.id.change_pass);
        UserPhone= (EditText) findViewById(R.id.change_phone);
        UserEmail= (EditText) findViewById(R.id.change_email);
        UserAddress= (EditText) findViewById(R.id.change_address);
        Changebutton= (Button) findViewById(R.id.change);
        touxiang= (RoundImageView) findViewById(R.id.ivtouxiang);
        imageButtonBack = (ImageButton) findViewById(R.id.imageButtom_back);
        changtou= (TextView) findViewById(R.id.changtou);
    }

    @Override
    public void onSuccess(Object o, int flag) {
        if (flag == 2) {
            GetInfo getInfo = (GetInfo) o;
            UserName.setText(getInfo.getU_name());
            PassWord.setText(getInfo.getU_pass());
            UserPhone.setText(getInfo.getU_phone());
            UserEmail.setText(getInfo.getU_email());
            UserAddress.setText(getInfo.getU_address());
            String headpic = BASE_URI+"photo/" + getInfo.getU_pic();
//                Picasso.with(MyFragment.this.getActivity()).load(headpic).into(imageView);
            Picasso.with(context).load(headpic).into(touxiang);
        }
        if (flag == 3) {
            //修改个人信息
            SampleInfo sampleInfo = (SampleInfo) o;
            if (sampleInfo.getSuccess().equals("0")) {
                Toast.makeText(UpdateInfoActivity.this, "修改失败", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(UpdateInfoActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onFail() {

    }
}
